//
//  ShareLayout.m
//  MMLOOK
//
//  Created by dllo on 15/9/1.
//  Copyright (c) 2015年 武俊娥. All rights reserved.
//

#import "ShareLayout.h"
#define RealWidth 130 *  [UIScreen mainScreen].bounds.size.width / 375

@interface ShareLayout ()

@property (nonatomic, assign) CGFloat height;

@end

@implementation ShareLayout

- (void)dealloc
{
    [_layoutArray release];
    [_array release];
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
    
    [self calculatorHeight];
}

//计算高度
- (void)calculatorHeight
{
    NSInteger itemNum = [self.collectionView numberOfItemsInSection:0];
    
    CGFloat realWidth = (self.collectionView.frame.size.width - 30) / 2;
    //设置中间变量存储上一个的高度
    CGFloat offLeft = 0;
    CGFloat offRight = 0;
    
    self.array = [NSMutableArray array];
    
    for (int i = 0; i < itemNum; i++) {
        
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        
        NSDictionary *dic = [self.layoutArray objectAtIndex:i];
        CGFloat width = [[dic objectForKey:@"width"] floatValue];
        CGFloat height = [[dic objectForKey:@"height"] floatValue];
        
        CGFloat realHeight = height * realWidth / width;
        
        if (!isnan(realHeight)) {// 函数用于检查其参数是否是非数字值
            
            if (i % 2 == 0) {
                
                att.frame = CGRectMake(10, 10 + offLeft, realWidth, realHeight);
                offLeft += realHeight + 10;
            } else {
                
                att.frame = CGRectMake(20 + realWidth, 10 + offRight, realWidth, realHeight);
                offRight += realHeight + 10;
            }
        }
        
        self.height = offLeft > offRight ? offLeft : offRight;
        
        [self.array addObject:att];
    }
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *currentArray = [NSMutableArray array];
    
    for (UICollectionViewLayoutAttributes *att in self.array) {
        
        if (CGRectIntersectsRect(att.frame, rect) || CGRectContainsRect(att.frame, rect)) {
            
            [currentArray addObject:att];
        }
    }
    return currentArray;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.array objectAtIndex:indexPath.item];
}

//滚动大小
- (CGSize)collectionViewContentSize
{
    return CGSizeMake(self.W, self.height);
}

@end
